package com.kai.server.exception.handler;

import com.kai.common.domain.Message;
import com.kai.common.domain.Response;
import com.kai.common.domain.ResponseHeader;
import com.kai.common.enumeration.ResponseType;
import com.kai.common.utils.ProtoStuffUtil;
import com.kai.server.property.PromptMsgProperty;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * <p>Project: furina-tea-party </p>
 * <p>Description: </p>
 * <p>Copyright (c) 2024 Karrytech (Shanghai/Beijing) Co., Ltd.</p>
 * <p>All Rights Reserved.</p>
 *
 * @author <a href="mailto:zhangkai@karrytech.com">Zhang Kai</a>
 */
@Component("interruptedExceptionHandler")
public class InterruptedExceptionHandler {
    public void handle(SocketChannel channel, Message message) {
        try {
            byte[] response = ProtoStuffUtil.serialize(
                    new Response(
                            ResponseHeader.builder()
                                    .type(ResponseType.PROMPT)
                                    .sender(message.getHeader().getSender())
                                    .timestamp(message.getHeader().getTimestamp()).build(),
                            PromptMsgProperty.SERVER_ERROR.getBytes(PromptMsgProperty.charset)));
            channel.write(ByteBuffer.wrap(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}